package com.briup.MR.funMR;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.chain.ChainMapper;
import org.apache.hadoop.mapreduce.lib.chain.ChainReducer;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.map.InverseMapper;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.mapreduce.lib.reduce.LongSumReducer;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import java.io.IOException;

/**
 * yarn jar HdfsClientDemo-1.0-SNAPSHOT.jar com.briup.MR.funMR.ChainMR -D input=/user/hdfs/patent -D output=/user/hdfs/chain_result
 * */
public class ChainMR extends Configured implements Tool {
    static class ChainMRMapper extends Mapper<Text,Text,Text, LongWritable>{
        @Override
        protected void map(Text key, Text value, Context context) throws IOException, InterruptedException {
            context.write(key,new LongWritable(1));
        }
    }
    public int run(String[] strings) throws Exception {
        Configuration conf = getConf();
        String input = conf.get("input");
        String output = conf.get("output");
        //设置拆分标准
        conf.set("mapreduce.input.keyvaluelinerecordreader.key.value.separator",",");

        Job job = Job.getInstance(conf);
        job.setJarByClass(this.getClass());
        job.setJobName("ChainMR");
        //添加交换键值的mapper
        ChainMapper.addMapper(job, InverseMapper.class,Text.class,Text.class,Text.class,Text.class,conf);
        //设置值为1的map
        ChainMapper.addMapper(job,ChainMRMapper.class,Text.class,Text.class,Text.class, LongWritable.class,conf);
        //设置reduce
        ChainReducer.setReducer(job, LongSumReducer.class,Text.class,LongWritable.class,Text.class,LongWritable.class,conf);
        //添加交换键值的map
        ChainReducer.addMapper(job,InverseMapper.class,Text.class,LongWritable.class,LongWritable.class,Text.class,conf);

        job.setInputFormatClass(KeyValueTextInputFormat.class);
        job.setOutputFormatClass(TextOutputFormat.class);
        KeyValueTextInputFormat.addInputPath(job,new Path(input));
        TextOutputFormat.setOutputPath(job,new Path(output));
        return job.waitForCompletion(true)?0:-1;
    }

    public static void main(String[] args) throws Exception {
        System.exit(new ToolRunner().run(new ChainMR(),args));
    }
}
